package com.jt.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jt.mapper.ItemDescMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.service.ItemService;
import com.jt.vo.EasyUITable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jt.mapper.ItemMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {
	
	@Autowired
	private ItemMapper itemMapper;

	@Autowired
	private ItemDescMapper itemDescMapper;

	@Override
	public EasyUITable findItemByPage(Integer page, Integer rows) {
		Long total = Long.valueOf(itemMapper.selectCount(null));
		long startIndex = (page-1)*rows;
		List<Item> records = itemMapper.findItemByPage(startIndex, rows);
		return new EasyUITable(total, records);
	}

	@Transactional
	@Override
	public void saveItem(Item item, ItemDesc itemDesc) {
		Date date = new Date();
		item.setStatus(1).setCreated(date).setUpdated(date);
		itemMapper.insert(item);
		itemDesc.setItemId(item.getId());
		itemDescMapper.insert(itemDesc);
	}

	@Transactional
	@Override
	public void updateItem(Item item, ItemDesc itemDesc) {
		itemMapper.updateById(item);
		itemDesc.setItemId(item.getId());
		itemDescMapper.updateById(itemDesc);
	}

	@Transactional
	@Override
	public void deleteItems(Long[] ids) {
		List<Long> longList = Arrays.asList(ids);
		itemMapper.deleteBatchIds(longList);
		itemDescMapper.deleteBatchIds(longList);
	}

	@Override
	public void updateStatus(Integer status, Long[] ids) {
		Item item = new Item();
		item.setStatus(status);
		UpdateWrapper<Item> updateWrapper = new UpdateWrapper<>();
		updateWrapper.in("id", Arrays.asList(ids));
		itemMapper.update(item, updateWrapper);
	}

	@Override
	public ItemDesc findItemDescById(Long itemId) {
		return itemDescMapper.selectById(itemId);
	}
}
